<template>
  <el-dialog :title="$t('common.operation')" :visible.sync="visibleModal" class="el-dialog-normal">
    <div style="margin-bottom: 80px">
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        inline
        class="dialog-form-two"
      >
        <el-form-item
          v-show="warehouseSelectShow"
          :label="$t('common.selectWare')"
          prop="warehouseId"
        >
          <WmsAreaCascader
            v-model="ruleForm.warehouseId"
            size="small"
          ></WmsAreaCascader>
        </el-form-item>
        <el-button type="primary" @click="addTags">{{ $t('order.addInst') }}</el-button>
      </el-form>
      <el-table ref="table" :data="InstructionsList">
        <el-table-column prop="instructions" :label="$t('order.inst')" width="100px">
          <template slot-scope="scope">
            <el-select
              v-model="scope.row.instructions"
              :placeholder="$t('common.placeholderSelect')"
              @change="selectChange(scope.row, scope.$index)"
            >
              <el-option
                v-for="item in InstructionOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="template" :label="$t('common.temp')" width="120px">
          <template slot-scope="scope">
            <el-link
              v-if="scope.row.template"
              type="primary"
              :href="scope.row.template"
            >
              {{ $t("common.downloadTemp") }}
            </el-link>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="fileList" :label="$t('common.fileName')" width="200px">
          <template slot-scope="scope">
            <el-upload
              v-if="
                scope.row.template || scope.row.instructions === 'RTVPICKUP'
              "
              v-loading="uploadLoading"
              :file-list="fileList"
              :auto-upload="true"
              :action="Url"
              accept=".xlsx,.xls"
              :data="{ row: scope.row }"
              :on-error="handleUploadError"
              :on-success="handleUploadSuccess(scope.row)"
              :headers="headers"
              style="text-align: left"
            >
              <el-button v-if="!scope.row.files" type="text">{{ $t('common.upload') }}</el-button>
              <el-tooltip
                v-else
                class="item"
                effect="dark"
                :content="scope.row.fileName"
                placement="bottom-end"
              >
                <span>{{ filterFileName(scope.row.fileName) }}</span>
              </el-tooltip>
            </el-upload>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="remark" :label="$t('common.remark')">
          <template slot-scope="scope">
            <el-input
              v-model="scope.row.remark"
              :placeholder="$t('common.pleaseInput')"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="operation" :label="$t('common.operation')">
          <template slot-scope="scope">
            <el-button
              type="text"
              @click.native.prevent="delTags(scope.$index, InstructionsList, scope.row.id)"
              >{{ $t('common.del') }}</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div
        class="foot-fixed-total"
        style="text-align: center; margin-top: 30px"
      >
        <el-button @click="visibleModal = false">{{ $t('common.cancel') }}</el-button>
        <el-button :loading="loading" type="primary" @click="submit('ruleForm')"
          >{{ $t('common.save') }}</el-button
        >
      </div>
    </div>
  </el-dialog>
</template>
<script>
import FormComponents from "@/components/FormComponents/index.vue";
import { changeStatus, getInstruct, changeInstruct, delInstruct, addInstruct } from "@/api/order/index.js";
import WmsAreaCascader from "@/components/WmsAreaCascader";
export default {
  props: {
    // 是否选择仓库
    warehouseSelectShow: {
      type: Boolean,
      default: false,
    },
    orderId: {
      type: String | Number,
      default: null,
    },
  },
  components: { FormComponents, WmsAreaCascader },
  watch: {
    orderId: {
      handler(v) {
        if(typeof v === "string" || typeof v === "number") {
            this.getList(v);
        }
      },
      immediate: true,
      deep: true
    },
  },
  computed: {
    rules() {
      if (!this.orderId) {
        return {
          warehouseId: [{ required: true, message: this.$t('common.placeholderSelect') }],
        };
      } else {
        return {};
      }
    },
  },
  data() {
    return {
      tableData: [],
      ruleForm: {},
      isedit: true,
      loading: false,
      visibleModal: false,
      warehouseList: [],
      InstructionOptions: [
        {
          label: this.$t('inst.InstructionOptions.LABELING'),
          value: "LABELING",
          fileName: "",
          fileUrl:
            "https://zjyg-yt.oss-cn-hangzhou.aliyuncs.com/scm/upload/20230921/xlsx/7239d6f501bb4358aedb60ab2646160c/换标登记表.xlsx",
        },
        {
          label: this.$t('inst.InstructionOptions.CHANGEBOX'),
          value: "CHANGEBOX",
          fileName: "",
          fileUrl: "",
        },
        {
          label: this.$t('inst.InstructionOptions.LABELCHANGE'),
          value: "LABELCHANGE",
          fileName: "",
          fileUrl:
            "https://zjyg-yt.oss-cn-hangzhou.aliyuncs.com/scm/upload/20230921/xlsx/7239d6f501bb4358aedb60ab2646160c/换标登记表.xlsx",
        },
        {
          label: this.$t('inst.InstructionOptions.DSORDER'),
          value: "DSORDER",
          fileName: "",
          fileUrl:
            "https://zjyg-yt.oss-cn-hangzhou.aliyuncs.com/scm/upload/20230921/xls/092b9403620e4be797de7e4aa3232713/DS订单拣货标模板.xls",
        },
        {
          label: this.$t('inst.InstructionOptions.RTVPICKUP'),
          value: "RTVPICKUP",
          fileName: "",
          fileUrl: "",
        },
        {
          label: this.$t('inst.InstructionOptions.CHANGEPRODUCT'),
          value: "CHANGEPRODUCT",
          fileName: "",
          fileUrl: "",
        },
        {
          label: this.$t('inst.InstructionOptions.DELIVERYFEE'),
          value: "DELIVERYFEE",
          fileName: "",
          fileUrl: "",
        },
        {
          label: this.$t('inst.InstructionOptions.stockAgeFee'),
          value: "stockAgeFee",
          fileName: "",
          fileUrl: "",
        },
        {
          label: this.$t('inst.InstructionOptions.warehouseOperationFee'),
          value: "warehouseOperationFee",
          fileName: "",
          fileUrl: "",
        },
        {
          label: this.$t('inst.InstructionOptions.materialCost'),
          value: "materialCost",
          fileName: "",
          fileUrl: "",
        }
      ],
      InstructionsValue: null,
      InstructionsList: [],
      headers: {
        // Authorization: getToken(),
      },
      uploadLoading: false,
      fileList: [],
      uploadMsg: [],
      Url: "https://recruitr.guanyunart.com/api/recruitr/upload/uploadFile",
      params: {},
    };
  },
  methods: {
    open() {
      this.visibleModal = true;
    },
    close() {
      this.visibleModal = false;
      this.getList(this.orderId)
    },
    getList(v) {
      getInstruct({orderId: v}).then((res) => {
        this.InstructionsList = res.content;
      });
    },
    setData(data) {
      const {
        id,
        receiverName,
        receiverPhone,
        receiverEmail,
        receiverPostCode,
        receiverProvince,
        receiverCity,
        receiverDetailAddress,
      } = data;
      this.ruleForm = {
        id,
        receiverName,
        receiverPhone,
        receiverEmail,
        receiverPostCode,
        receiverProvince,
        receiverCity,
        receiverDetailAddress,
      };
      this.visibleModal = true;
    },
    addTags() {
      this.InstructionsList.push({
        instructions: "",
        title: "",
        template: "",
        files: "",
        fileName: "",
        remark: "",
      });
    },
    delTags(index, rows, id) {
      rows.splice(index, 1);
    //   delInstruct(id).then(res=>{
    //     if(res) {
    //         this.$message.success(this.$t('common.succcessInfo'))
    //     }
    //   })
    },
    selectChange(row, index) {
      const url = this.InstructionOptions.find(
        (a) => a.value === row.instructions
      ).fileUrl;
      if (url) {
        this.$refs.table.tableData[index].template = url;
      } else {
        this.$refs.table.tableData[index].template = null;
      }
    },
    filterFileName(fileName) {
      const maxLength = 22; // 最大长度，包括省略号
      let truncatedName = fileName;
      if (fileName.length > maxLength) {
        const prefixLength = Math.floor((maxLength - 3) / 2); // 前缀长度
        const suffixLength = maxLength - prefixLength - 3; // 后缀长度
        const prefix = fileName.substr(0, prefixLength);
        const suffix = fileName.substr(fileName.length - suffixLength);
        truncatedName = `${prefix}...${suffix}`;
        return truncatedName;
      }
    },
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let data = this.ruleForm;
          this.loading = true;
          data.status = 1;
          let params = {
            id: data.id,
            status: data.status,
            instructList: this.$refs.table.tableData,
          };
          //   非详情页 加上仓库
          if (!this.orderId) {
            params.warehouseId = data.warehouseId[0];
            params.areaId = data.warehouseId[1];
          } else {
            // 详情页编辑，不区分状态
            params.orderId = this.orderId
            delete params.status;
          }
          params.instructList = params.instructList.map((item) => {
            const match = this.InstructionOptions.find(
              (option) => option.value === item.instructions
            ).label
            return {
              files: item.files,
              type: item.instructions,
              remark: item.remark,
              id: item.id ? item.id: '',
              title: match ? match.label : "",
            };
          });
        //   console.log('params', params)
        //   return
          changeInstruct(params)
            .then((res) => {
              this.loading = false;
              this.$message.success(this.$t('common.succcessInfo'));
              this.$emit("success");
              this.visibleModal = false;
            })
            .catch((e) => {
              this.loading = false;
            });
        }
      });
    },
    handleUploadProress(e, file, fileList) {
      this.uploadLoading = true;
    },
    handleUploadSuccess(row) {
      return (response, file, fileList) => {
        // 将上传的文件信息赋值给相应行的对象
        row.fileName = file.name;
        row.files = file.response.data;
      };
    },
    handleUploadError() {
      this.uploadLoading = false;
      this.fileList = [];
      this.$message({
        type: "error",
        message: this.$t('common.failedMsg'),
      });
    },
  },
};
</script>
<style scoped lang="scss">
::v-deep .el-link--inner {
  font-size: 12px;
}
</style>
  